package xhwl.insurance.ui;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.List;

import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.R;
import xhwl.insurance.adapter.FindDetailsAdapter;
import xhwl.insurance.customView.PlayerWebView;
import xhwl.insurance.dialog.VideoShareDialog;
import xhwl.insurance.http.api.GiveThumbs_upApi;
import xhwl.insurance.http.api.VideoDetailRelatedApi;
import xhwl.insurance.http.api.VideoDetailsApi;
import xhwl.insurance.http.bean.resp.ForumProductResp;
import xhwl.insurance.http.bean.resp.VideoListResp;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.pulltorefresh.PullToRefreshRecyclerView;
import xhwl.pulltorefresh.callback.PullToRefreshListener;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by fuyi on 2017/9/28.
 */

public class FindDetailsActivity extends BaseActivity implements PullToRefreshListener, View.OnClickListener {
    private ImageView mGoods, mShare, mBack;
    private TextView mGoodNum;
    private TextView mFindTitle, mTime;
    private PlayerWebView mWebView;
    private VideoShareDialog shareDialog;
    private String video_pic, video_url, thumbs_up, video_name, video_id;
    private ArrayList<VideoListResp> mList = new ArrayList<VideoListResp>();
    private PullToRefreshRecyclerView mRecyclerView;
    private ArrayList<ForumProductResp> datas = new ArrayList<>();

    int mPage = 1;
    private FindDetailsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finddetails);

    }

    @Override
    public void initViews() {
        mRecyclerView = (PullToRefreshRecyclerView) findViewById(R.id.recyclerview_fxd);
        mGoods = (ImageView) findViewById(R.id.iv_finddetails_good);
        mShare = (ImageView) findViewById(R.id.iv_finddetails_videoshare);
        mGoodNum = (TextView) findViewById(R.id.tv_finddetails_goodnum);
        mFindTitle = (TextView) findViewById(R.id.tv_finddetails_title);
        mTime = (TextView) findViewById(R.id.tv_finddetails_time);
        mWebView = (PlayerWebView) findViewById(R.id.videoWebView_finddetails);
        mBack = (ImageView) findViewById(R.id.iv_left_back);
        adapter = new FindDetailsAdapter(FindDetailsActivity.this, datas);
        mRecyclerView.setAdapter(adapter);
        initRecylerView();

    }

    private void initRecylerView() {
        //设置EmptyView
        View emptyView = View.inflate(FindDetailsActivity.this, R.layout.layout_empty_view, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        mRecyclerView.setEmptyView(emptyView);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(FindDetailsActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        //设置是否开启上拉加载
        mRecyclerView.setLoadingMoreEnabled(true);
        //设置是否开启下拉刷新
        mRecyclerView.setPullRefreshEnabled(true);
        //设置是否显示上次刷新的时间
        mRecyclerView.displayLastRefreshTime(false);
    }

    @Override
    protected void processOper() {

    }

    @Override
    public void initListener() {
        mGoods.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mRecyclerView.setPullToRefreshListener(this);
        adapter.setOnItemClickLitener(new FindDetailsAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                ForumProductResp  mForumProductResp = (ForumProductResp) datas.get(position);
                Intent intent = new Intent();
                intent.putExtra(ForumDetailNewActivity.EXTRA_DATA, mForumProductResp);
                intent.setClass(FindDetailsActivity.this, ForumDetailNewActivity.class);
                startActivity(intent);
            }
        });

    }


    @Override
    public void loadData() {
        getData();
        onWebView();
        getVideoDetailRelated(1);
    }

    @Override
    public void onRefresh() {
        getVideoDetailRelated(1);
    }

    @Override
    public void onLoadMore() {
        getVideoDetailRelated(mPage + 1);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_finddetails_good:
                initThumbs_Up();
                break;
            case R.id.iv_finddetails_videoshare:
                initShare();
                break;
            case R.id.iv_left_back:
                finish();
                break;
        }

    }

    private void initThumbs_Up() {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        GiveThumbs_upApi api = new GiveThumbs_upApi(video_id, member_id);
        HttpManager.getInstance().dealHttp(FindDetailsActivity.this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
                    mList.get(0).isSelected = !mList.get(0).isSelected;
                    int thumbs = Integer.valueOf(mList.get(0).getTHUMBS_UP()).intValue();
                    int thubs2 = thumbs += 1;
                    int thubs3 = thumbs -= 1;
//
                    if (mList.get(0).getTHUMBS_FLAG().equals("1")) {
                        int thubs4 = thumbs -= 1;
                        int thubs5 = thumbs += 1;
                        mGoods.setImageResource(mList.get(0).isSelected ? R.drawable.icon_thumbs_up : R.drawable.icon_thumbs_up2);
                        mGoodNum.setText(mList.get(0).isSelected ? thubs4 + "" : thubs5 + "");
                    } else {
                        mGoods.setImageResource(mList.get(0).isSelected ? R.drawable.icon_thumbs_up2 : R.drawable.icon_thumbs_up);
                        mGoodNum.setText(mList.get(0).isSelected ? thubs2 + "" : thubs3 + "");
                    }

                } else {
                    ToastUtil.showToast(FindDetailsActivity.this, resp.message);
                }

            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
            }
        });
    }


    public void getData() {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        String video_ids = getIntent().getStringExtra("VIDEO_ID");
        String video_names = getIntent().getStringExtra("VIDEO_NAME");
        VideoDetailsApi api = new VideoDetailsApi(member_id, video_ids);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<ArrayList<VideoListResp>>>() {

            @Override
            public void onNext(HttpResp<ArrayList<VideoListResp>> resp) {
                if (resp.isOk()) {
                    mList.addAll(resp.data);
                    video_pic = resp.data.get(0).getVIDEO_PIC();
                    video_url = resp.data.get(0).getVIDEO_URL();
                    video_name = resp.data.get(0).getVIDEO_NAME();
                    video_id = resp.data.get(0).getVIDEO_ID();
                    thumbs_up = resp.data.get(0).getTHUMBS_UP();


                    mWebView.setCoverImageUrl(video_pic);
                    mWebView.setVideoUrl(video_url);
                    mFindTitle.setText(video_name);
                    mTime.setText(resp.data.get(0).getCREATE_DATE());
                    mGoodNum.setText(thumbs_up);

                    if (resp.data.get(0).getTHUMBS_FLAG().equals("1")) {
                        mGoods.setImageResource(R.drawable.icon_thumbs_up2);
                    } else if (resp.data.get(0).getTHUMBS_FLAG().equals("0")) {
                        mGoods.setImageResource(R.drawable.icon_thumbs_up);
                    } else {

                    }

                } else {
                    ToastUtil.showToast(FindDetailsActivity.this, resp.message);
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
            }
        });
    }

    public void getVideoDetailRelated(final int page_num) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        String video_ids = getIntent().getStringExtra("VIDEO_ID");
        VideoDetailRelatedApi api = new VideoDetailRelatedApi(member_id, video_ids, page_num);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<ArrayList<ForumProductResp>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<ForumProductResp>> resp) {
                if (page_num == 1) { //下拉刷新操作
                    if (resp.isOk()) {
                        if (resp != null && resp.data.size() > 0) {
                            mRecyclerView.setRefreshComplete();
                            mPage = 1;
                            datas.clear();
                            datas.addAll(resp.data);
                            adapter.notifyDataSetChanged();

                        } else {
                            mRecyclerView.setRefreshFail();
                        }
                    } else {
                        ToastUtil.showToast(FindDetailsActivity.this, resp.message);
                    }
                } else {
                    if (resp != null) {
                        mRecyclerView.setLoadMoreComplete();
                        if (resp.isOk()) {
                            if (resp.data != null && resp.data.size() > 0) {
                                mPage = page_num;
                                datas.addAll(resp.data);
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUtil.showToast(FindDetailsActivity.this, getString(R.string.no_more_data));
                            }
                        } else {
                            ToastUtil.showToast(FindDetailsActivity.this, resp.message);
                        }
                    } else {
                        mRecyclerView.setLoadMoreFail();
                    }

                }

            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                if (page_num == 1) {
                    mRecyclerView.setRefreshFail();

                } else {
                    mRecyclerView.setLoadMoreFail();
                }
            }
        });
    }

    private void initShare() {
        shareDialog = new VideoShareDialog(FindDetailsActivity.this);
        shareDialog.setCancelable(false);
        shareDialog.setCanceledOnTouchOutside(false);
        View dialog = View.inflate(FindDetailsActivity.this, R.layout.dialog_videoshare, null);
        RelativeLayout mWxCircle = (RelativeLayout) dialog.findViewById(R.id.rl_wxcircle);
        RelativeLayout mWechat = (RelativeLayout) dialog.findViewById(R.id.rl_wechat);
        RelativeLayout mCopy = (RelativeLayout) dialog.findViewById(R.id.rl_copy);
        TextView mCancel = (TextView) dialog.findViewById(R.id.btn_videocancel);
        shareDialog.setContentView(dialog);
        shareDialog.show();
        mWebView.Suspend();

        final UMImage image = new UMImage(FindDetailsActivity.this, video_pic);
        mWxCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new ShareAction(FindDetailsActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
                        .withTitle(video_name)
                        .withTargetUrl(video_url)
                        .withText(video_url)
                        .withMedia(image)
                        .share();
            }
        });

        mWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new ShareAction(FindDetailsActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(shareListener)
                        .withTitle(video_name)
                        .withTargetUrl(video_url)
                        .withText(video_url)
                        .withMedia(image)
                        .share();
            }
        });

        mCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUtil.isEmpty(video_url)) {
                    ClipboardManager cmb = (ClipboardManager) FindDetailsActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setText(video_url);
                    ToastUtil.showToast(FindDetailsActivity.this, "链接已复制");
                } else {
                    ToastUtil.showToast(FindDetailsActivity.this, "该视频没有链接");
                }
            }
        });

        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareDialog.dismiss();
            }
        });


    }


    private void onWebView() {
        mWebView.setCallBack(new PlayerWebView.CallBack() {
            @Override
            public void onPlayBtnClick() {
                mWebView.play();
            }
        });
    }

    @Override
    public void onPause() {
        pauseCurrentVideo();

        super.onPause();
    }

    public void pauseCurrentVideo() {
        if (mWebView != null) {
            mWebView.pause();
            mWebView = null;
        }
    }

    private UMShareListener shareListener = new UMShareListener() {

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showToast(FindDetailsActivity.this, "分享成功！");
            if (shareDialog != null && shareDialog.isShowing()) {
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtil.showToast(FindDetailsActivity.this, "分享失败！");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.showToast(FindDetailsActivity.this, "取消分享");

        }
    };


}
